package com.shxy.cloudclassroom.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * REST接口全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class RestExceptionHandler {

    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(value = {
            VerificationCodeErrorException.class,
            NotfoundVerificationCodeException.class,
            PasswordErrorException.class,
            UserNameAlreadyExistsException.class,
            UserNotfoundException.class
    })
    public ResponseEntity<Map<String, Object>> handleBusinessException(RuntimeException e) {
        log.error("业务异常: ", e);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", e.getMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<Map<String, Object>> handleIllegalArgumentException(IllegalArgumentException e) {
        log.error("参数校验异常: ", e);
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", "参数错误: " + e.getMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
    }

    /**
     * 处理系统异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleSystemException(Exception e) {
        log.error("系统异常: ", e);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", "系统异常，请联系管理员");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
    }
}